# Analysis_BonotFigure.R
# Nico Ravanilla, Michael Davidson & Allen Hicken
# September 2021
# Version 1.0
# Replication code


rm(list=ls())

library(RColorBrewer)
library(igraph)

# Local Machine
setwd("~/Google Drive/Project Networks_Sorg/Analyses/5_Analyses_033116/")

# Load Graph with Network Measures
load("build/output/bgyNet.Rda")

# Subset Graph to just Bgy Bonot
bonot <- induced.subgraph(bgyNet, V(bgyNet)[V(bgyNet)$BARANGAY=="BON-OT"])
	# Remove self-loops
	bonot <- simplify(bonot)

# Identify candidates in Bon-Ot for Bgy Captain 
bonotCands.vs <- V(bonot)[V(bonot)$PUNONG_BGY=="1"]
bonotCands <- which(V(bonot)$PUNONG_BGY=="1")

cols <- brewer.pal(length(bonotCands), "Set1")
V(bonot)$color[V(bonot)$PUNONG_BGY=="1"] <- cols

# Which candidate is someone closer too?
for(i in bonotCands){
	bonot <- set.vertex.attribute(bonot,
		name=paste0("shortest", V(bonot)$name[i]),
		value=shortest.paths(bonot, v=V(bonot),
			to=i, mode="all"))
}

# Helper Matrix
(t<-cbind(
	shortest37=V(bonot)$shortest37,
	shortest38=V(bonot)$shortest38,
	shortest39=V(bonot)$shortest39,
	shortest40=V(bonot)$shortest40))

t2 <- list()
for(i in 1:nrow(t)){
	m <- min(t[i,])
	t2[[i]] <- names(which(t[i,]==m))
}
t2 <- lapply(t2, function(x){gsub(x=x, pattern="shortest", replacement="")})
V(bonot)$tied <- unlist(lapply(t2, function(x){
	length(x)>1
}))

V(bonot)$closest <- unlist(lapply(t2, function(x){x[1]})) 
	V(bonot)$closest[which(V(bonot)$tied==TRUE)] <- NA

cheat <- cbind(V(bonot)$color[V(bonot)$PUNONG_BGY=="1"], V(bonot)[which(V(bonot)$PUNONG_BGY=="1")]$name)

for(i in 1:nrow(cheat)){
	V(bonot)$color[V(bonot)$closest==cheat[i,2]] <- cheat[i,1]
}
V(bonot)$color[is.na(V(bonot)$closest)] <- "white"

V(bonot)$vertex.size <- ifelse(V(bonot)$PUNONG_BGY == "1", 12, 6)
V(bonot)$shape <- ifelse(V(bonot)$PUNONG_BGY == "1", "square", "circle")

pdf(file="analyses/output/figures/bonot.pdf", width=9, height=7)
	set.seed(12345)
	plot(bonot, vertex.size=V(bonot)$vertex.size, vertex.label=NA)
dev.off()



pdf(file="analyses/output/figures/degreeDistribution.pdf", width=9, height=6)
	hist(d$degree, main="", xlab="Degree")
dev.off()